<?php

/**
 * Zeed Platform Project
 * Based on Zeed Framework & Zend Framework.
 *
 * LICENSE
 * http://www.zeed.com.cn/license/
 *
 * @category Zeed
 * @package Zeed_ChangeMe
 * @subpackage ChangeMe
 * @copyright Copyright (c) 2010 Zeed Technologies PRC Inc. (http://www.zeed.com.cn)
 * @author Zeed Team (http://blog.zeed.com.cn)
 * @since 2010-12-6
 * @version SVN: $Id$
 */
class ContentTempController extends ArchiveAdminAbstract
{
    protected $perpage = 20;

    /**
     * 案件列表 - 临时用户组
     */
    public function index()
    {
        $this->addResult(self::RS_SUCCESS, 'json');

        /* 接收参数 */
        $ordername = $this->input->get('ordername', null);
        $orderby = $this->input->get('orderby', null);
        $page = (int)$this->input->get('pageIndex', 0);
        $perpage = (int)$this->input->get('pageSize', $this->perpage);
        $key = trim($this->input->get('key'));
        $time_start = $this->input->get('time_start');
        $time_end = $this->input->get('time_end');
        $category_name = $this->input->get('category_name');
        $department_name = $this->input->get('department_name');

        /* ajax 加载数据 */
        if ($this->input->isAJAX()) {
            $offset = $page * $perpage;
            $page = $page + 1;

            /* 组织查询条件 */
            $timenow = Util_Timer::getMicrotime();
            $where = array('status' => 1, 'share_to' => $this->_userid);
            $where['$and'][] = array(
                '$or' => array(
                    array('exptime' => 0),
                    array('exptime' => ['$gte' => $timenow]),
                )
            );
            
            if ($time_start && $time_end) {
                /* 处理时间排序 */
                $time_se = array($time_start, $time_end);
                asort($time_se);
                $time_se = array_values($time_se);
                $time_start = $time_se[0];
                $time_end = $time_se[1];

                $where['$and'][] = array(
                    '$and' => array(
                        array('tte' => ['$gte' => $time_start]),
                        array('tte' => ['$lte' => $time_end]),
                    )
                );
            } else {
                if ($time_start) {
                    $where['tte'] = ['$gte' => $startime];
                }

                if ($time_end) {
                    $where['tte'] = ['$lte' => $endtime];
                }
            }
            if ($category_name) {
                $where['$and'][] = array('category_name' => new MongoRegex("/$category_name/i"));
            }
            if ($department_name) {
                $where['$and'][] = array('department_name' => new MongoRegex("/$department_name/i"));
            }
            if ($key) {
                $where['$and'][] = array(
                    '$or' => array(
                        array('sn' => new MongoRegex("/$key/i")),
                        array('title' => new MongoRegex("/$key/i")),
                        array('description' => new MongoRegex("/$key/i")),
                        array('label' => new MongoRegex("/$key/i")),
                    )
                );
            }
            $order = array('ctime' => 'DESC');

            /* 执行查询 */
            $content = Archive_Model_Share::instance()->fetchByWhere($where, $order, $perpage, $offset);
            $data['count'] = Archive_Model_Share::instance()->getCount($where);

            /* 处理其他一些信息 */
            if (! empty($content)) {
                foreach ($content as $k => &$v) {
                    /* 处理案件名称 */
                    $v['title_sub'] = $v['title'];
                    if (mb_strlen($v['title_sub']) > 16) {
                        $v['title_sub'] = mb_substr($v['title_sub'], 0, 16);
                    }

                    /* 处理过期时间 */
                    if (! $v['exptime']) {
                        $v['exptime'] = '永不过期';
                    } elseif (strlen($v['exptime']) == 13) {
                        $v['exptime'] = date(DATETIME_FORMAT, $v['exptime'] / 1000);
                    } else {
                        $v['exptime'] = date(DATETIME_FORMAT, $v['exptime']);
                    }

                    /* 处理行动次数 */
                    $where_card = array('sn' => $v['sn'], 'status' => 1);
                    $v['count_card'] = Archive_Model_Card::instance()->getCount($where_card);

                    /* 获取原案件 ID */
                    $v['_id_y'] = '';
                    $archive_y = Archive_Model_Content::instance()->fetchByFV('sn', $v['sn']);
                    if (!empty($archive_y)) {
                        $v['_id_y'] = $archive_y[0]['_id'];
                    }
                }
            }

            $data['content'] = $content ? $content : array();
        }
        
        /* 获取案件类型 */
        $categories = Archive_Model_Category::instance()->getAllCategoriesForSelect();
        
        /* 获取承办部门 */
        $where_department = array('status' => 1);
        $order_department = "sort_order ASC";
        $departments = Archive_Model_Department::instance()->fetchByWhere($where_department, $order_department);

        $data['categories'] = $categories;
        $data['departments'] = $departments;

        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'contenttemp.index');
        return parent::multipleResult(self::RS_SUCCESS);
    }

    /**
     * 详情
     */
    public function detail()
    {
        $this->addResult(self::RS_SUCCESS, 'json');

        /* 接收参数 */
        $_id = $this->input->get('_id');
        $card_id = $this->input->query('card_id');

        /* 获取案件分享信息 */
        $share_info = Archive_Model_Share::instance()->fetchByPK($_id);
        if (empty($share_info)) {
            throw new Zeed_Exception('查无此分享的案件信息');
        }
        $share_info = $share_info[0];

        /* 查询原案件详情 */
        $content = Archive_Model_Content::instance()->fetchByFV('sn', $share_info['sn']);
        if (empty($content) || ($content[0]['status'] != 1 && $content[0]['status'] != -2)) {
            throw new Zeed_Exception('查无此案件');
        }
        $content = $content[0];

        /* 获取相关行动 */
        $where_card = array('sn' => $content['sn'], 'status' => 1);
        $cards = Archive_Model_Card::instance()->fetchByWhere($where_card);

        /* 处理行动相关信息 */
        if (! empty($cards)) {
            foreach ($cards as $k => &$v) {
                /* 获取案件地点信息 */
                $region_info_card = Trend_Model_Region::instance()->fetchByPK($v['region_id']);
                $v['region_hid'] = $region_info_card[0]['hid'];
                $v['region_hid_arr'] = explode(':', $v['region_hid']);

                /* 获取父级目录信息以及子目录信息 */
                $folders = $this->_getFirstFolders($v);
                $v['parent_folder'] = $folders['parent_folder'];
                $v['child_folders'] = $folders['child_folders'];
                $v['child_folders_forselect'] = $folders['child_folders_forselect'];

                /* 处理附件 - 照片 */
                if ($v['attachments_img']) {
                    $attachments_img = explode(',', $v['attachments_img']);
                    $v['attachments_image_info'] = Attachment_Model_Content::instance()->fetchByPK($attachments_img);

                    /* 处理附件相关信息 */
                    if (! empty($v['attachments_image_info'])) {
                        foreach ($v['attachments_image_info'] as $kk => $vv) {
                            /* 过滤 */
                            if ($vv['status'] != 1) {
                                unset($v['attachments_image_info'][$kk]);
                                continue;
                            }

                            /* 处理时间 */
                            $v['attachments_image_info'][$kk]['ctime'] = Util_Timer::formatMicrotime($vv['ctime'], 'Y-m-d H:i:s');

                            /* 处理容量 */
                            $v['attachments_image_info'][$kk]['filesize_format'] = Util_File::formatFilesize($vv['filesize']);
                        }
                    }
                }

                /* 处理附件 - 录音 */
                if ($v['attachments_audio']) {
                    $attachments_audio = explode(',', $v['attachments_audio']);
                    $v['attachments_audio_info'] = Attachment_Model_Content::instance()->fetchByPK($attachments_audio);

                    /* 处理附件相关信息 */
                    if (! empty($v['attachments_audio_info'])) {
                        foreach ($v['attachments_audio_info'] as $kk => $vv) {
                            /* 过滤 */
                            if ($vv['status'] != 1) {
                                unset($v['attachments_audio_info'][$kk]);
                                continue;
                            }

                            /* 处理时间 */
                            $v['attachments_audio_info'][$kk]['ctime'] = Util_Timer::formatMicrotime($vv['ctime'], 'Y-m-d H:i:s');

                            /* 处理扩展信息 */
                            $v['attachments_audio_info'][$kk]['extra'] = $vv['extra'] ? json_decode($vv['extra'], true) : array();

                            /* 处理容量 */
                            $v['attachments_audio_info'][$kk]['filesize_format'] = Util_File::formatFilesize($vv['filesize']);
                        }
                    }
                }

                /* 处理附件 - 录像 */
                if ($v['attachments_video']) {
                    $attachments_video = explode(',', $v['attachments_video']);
                    $v['attachments_video_info'] = Attachment_Model_Content::instance()->fetchByPK($attachments_video);

                    /* 处理附件相关信息 */
                    if (! empty($v['attachments_video_info'])) {
                        foreach ($v['attachments_video_info'] as $kk => $vv) {
                            /* 过滤 */
                            if ($vv['status'] != 1) {
                                unset($v['attachments_video_info'][$kk]);
                                continue;
                            }

                            /* 处理时间 */
                            $v['attachments_video_info'][$kk]['ctime'] = Util_Timer::formatMicrotime($vv['ctime'], 'Y-m-d H:i:s');

                            /* 处理扩展信息 */
                            $v['attachments_video_info'][$kk]['extra'] = $vv['extra'] ? json_decode($vv['extra'], true) : array();

                            /* 处理容量 */
                            $v['attachments_video_info'][$kk]['filesize_format'] = Util_File::formatFilesize($vv['filesize']);
                        }
                    }
                }
            }
        }

        $data = array(
            'content' => $content,
            'card_id' => $card_id,
            'cards' => $cards
        );

        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'contenttemp.detail');
        return parent::multipleResult(self::RS_SUCCESS);
    }

    /**
     * 获取根目录下的子目录信息
     *
     * @param array $card_info 资料卡信息
     * @return boolean
     */
    protected function _getFirstFolders($card_info)
    {
        /* 处理照片类型 */
        $where_folder_image = array(
                'parent_id' => 0,
                'card_id' => $card_info['_id'],
                'title' => date('Y-m-d', intval($card_info['ctime'] / 1000)) . '_image_' . $card_info['_id']
        );
        $folder_info_image = Attachment_Model_Folder::instance()->fetchByWhere($where_folder_image);

        $where_child_folders_image = array(
                'parent_id' => $folder_info_image[0]['fid'],
                'card_id' => $card_info['_id'],
                'status' => 1
        );
        $child_folders['image'] = Attachment_Model_Folder::instance()->fetchByWhere($where_child_folders_image);

        /* 处理录音类型 */
        $where_folder_audio = array(
                'parent_id' => 0,
                'card_id' => $card_info['_id'],
                'title' => date('Y-m-d', intval($card_info['ctime'] / 1000)) . '_audio_' . $card_info['_id']
        );
        $folder_info_audio = Attachment_Model_Folder::instance()->fetchByWhere($where_folder_audio);

        $where_child_folders_audio = array(
                'parent_id' => $folder_info_audio[0]['fid'],
                'card_id' => $card_info['_id'],
                'status' => 1
        );
        $child_folders['audio'] = Attachment_Model_Folder::instance()->fetchByWhere($where_child_folders_audio);

        /* 处理录像类型 */
        $where_folder_video = array(
                'parent_id' => 0,
                'card_id' => $card_info['_id'],
                'title' => date('Y-m-d', intval($card_info['ctime'] / 1000)) . '_video_' . $card_info['_id']
        );
        $folder_info_video = Attachment_Model_Folder::instance()->fetchByWhere($where_folder_video);

        $where_child_folders_video = array(
                'parent_id' => $folder_info_video[0]['fid'],
                'card_id' => $card_info['_id'],
                'status' => 1
        );
        $child_folders['video'] = Attachment_Model_Folder::instance()->fetchByWhere($where_child_folders_video);

        /* 汇总返回信息 */
        $folders = array(
                'parent_folder' => array(
                        'image' => $folder_info_image[0],
                        'audio' => $folder_info_audio[0],
                        'video' => $folder_info_video[0]
                ),
                'child_folders' => $child_folders
        );
        return $folders;
    }

    /**
     * 下载
     */
    public function download()
    {
        /* 接收参数 */
        $params = array(
            '_id' => $this->input->get('_id', ''),
            'content_id' => $this->input->get('content_id', ''),
            'card_id' => $this->input->get('card_id', ''),
            'type' => $this->input->get('type', '')
        );
        foreach ($params as $k => $v) {
            if (! $v) {
                unset($params[$k]);
            }
        }

        /* 跳转 */
        $download_url = Zeed_Config::loadGroup('urlmapping.download_url');
        header('Location: ' . $download_url . '?' . http_build_query($params));
    }
}

// End ^ LF ^ encoding
